import { generateQRCode } from '@/services/helperService';
import { Button, Modal } from 'antd';
import React, { useEffect, useState } from 'react';

interface Props {
  modalVisible: boolean;
  onCancel: () => void;
  boardId: number;
}

const QRCodeModal: React.FC<Props> = (props) => {
  const { modalVisible, onCancel, boardId } = props;
  const [imgUrl, setImgUrl] = useState<string>('');

  const generateCode = async () => {
    if (!boardId) {
      return;
    }

    const { Items } = await generateQRCode(boardId);
    setImgUrl(Items[0])
  }

  const downloadImage = (imageUrl: string, name: string) => {
    const image = new Image();
    image.setAttribute('crossOrigin', 'anonymous');
    image.onload = function () {
      const canvas = document.createElement('canvas');
      canvas.width = image.width;
      canvas.height = image.height;
      const context = canvas.getContext('2d');
      if (!context) {
        return;
      }

      context.drawImage(image, 0, 0, image.width, image.height);
      // 得到图片的base64编码数据
      const url = canvas.toDataURL('image/png');

      // 生成一个a元素
      const a = document.createElement('a');
      // 创建一个单击事件
      const event = new MouseEvent('click');
      a.download = name;
      // 将生成的URL设置为a.href属性
      a.href = url;
      // 触发a的单击事件
      a.dispatchEvent(event);
    };
    image.src = imageUrl;
  }

  // @ts-ignore
  useEffect(() => {
    generateCode();
  }, [boardId])

  return (<Modal
    width={500}
    destroyOnClose
    title="二维码"
    open={modalVisible}
    onCancel={() => onCancel()}
    footer={[
      <Button
        key="1"
        type="primary"
        style={{ marginTop: '20px' }}
        onClick={() => { downloadImage(imgUrl, '') }}
      >
        下载
      </Button>,
      <Button key="back" onClick={() => onCancel()}>
        关闭
      </Button>,
    ]}
  >
    <div style={{ flex: '1', flexDirection: 'column', display: 'flex' }}>
      <img style={{ alignItems: 'center', flex: '1', display: 'flex', width: '200px', marginLeft: '130px' }} alt='' src={imgUrl} />
    </div>
  </Modal>)
}

export default QRCodeModal;

